﻿using FirstFloor.ModernUI.Presentation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

using System.Windows.Documents;
using System.Windows.Documents.Serialization;
using System.Windows.Markup;
using System.Windows;

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using FirstFloor.ModernUI.Windows.Controls;
using System.Diagnostics;

using Microsoft.Practices.Unity;
using appCtx = EasyInvoice.ApplicationContext.AppContext;


namespace EasyInvoice.WPF.ViewModel
{
    class InvoiceListNewViewModel : NotifyPropertyChanged
    {
        private Services.InvoicesService _serviceInvoices;

        #region Invoice List

        private ObservableCollection<InvoiceViewModel> _invoices = new ObservableCollection<InvoiceViewModel>();

        public ObservableCollection<InvoiceViewModel> Invoices
        {

            get
            {
                this._invoices = GetInvoices();
                return this._invoices;
            }
            set
            {
                this._invoices = value;
                this.OnPropertyChanged("Invoices");
            }
        }

        public InvoiceViewModel SelectedInvoice
        { get; set; }
        #endregion

        public InvoiceListNewViewModel()
        {
            this._serviceInvoices = appCtx.Instance.IoC.Resolve<Services.InvoicesService>();
        }

        private ObservableCollection<InvoiceViewModel> GetInvoices()
        {
            var returnValue = new ObservableCollection<InvoiceViewModel>();
            var invoices = this._serviceInvoices.GetAll();

            invoices = from Model.Invoice c in invoices 
                       where c.Date >= _startDate 
                       && c.Date <= _endDate 
                       && c.Number.Contains(_number) 
                       && (_filterClient.Id==0?0:_filterClient.Id) == (_filterClient.Id==0?0:c.ClientId)
                       && (_filterSeller.Id == 0 ? 0 : _filterSeller.Id) == (_filterSeller.Id == 0 ? 0 : c.SellerId)
                       select c;
            invoices.ToList().ForEach(invoice => returnValue.Add(new InvoiceViewModel(invoice)));

            return returnValue;
        }

        #region Filter properties
        
        private DateTime _startDate = DateTime.Today.AddYears(-1);

        public DateTime StartDate
        {
            get
            {
                return this._startDate;
            }
            set
            {
                this._startDate = value;
                this.OnPropertyChanged("StartDate");
            }
        }

        private DateTime _endDate = DateTime.Today;
        
        public DateTime EndDate
        {
            get
            {
                return this._endDate;
            }
            set
            {
                this._endDate = value;
                this.OnPropertyChanged("EndDate");
            }
        }

        private string _number = string.Empty;

        public string Number
        {
            get
            {
                return this._number;
            }
            set
            {
                this._number = value;
                this.OnPropertyChanged("Number");
            }
        }

        private ClientViewModel _filterClient = Repository.GetFilterClients().First(i => i.Id == 0);

        public ClientViewModel FilterClient
        {
            get
            {
                return this._filterClient;
            }
            set
            {
                this._filterClient = value;
                OnPropertyChanged("FilterClient");
            }

        }

        private ClientViewModel _filterSeller = Repository.GetFilterSellers().First(i => i.Id == 0);

        public ClientViewModel FilterSeller
        {
            get
            {
                return this._filterSeller;
            }
            set
            {
                this._filterSeller = value;
                OnPropertyChanged("FilterSeller");
            }

        }

        #endregion

        public bool CanAddInvoice
        {
            get
            {
                return ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ?
                    ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).AddInvoices : false;
            }
        }

        public bool CanDeleteInvoice
        {
            get
            {
                return ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ?
                    ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).DeleteInvoices : false;
            }
        }

        public bool CanEditInvoice
        {
            get
            {
                return !(((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ?
                    ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).EditInvoices : false);
            }
        }
        //for opening up the Add Client window
        //private ICommand showAddCommand;

        //public ICommand ShowAddCommand
        //{
        //    get
        //    {
        //        if (showAddCommand == null)
        //        {
        //            showAddCommand = new Common.CommandBase(
        //                i => this.AddInvoice(),
        //                i => ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ? ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).AddInvoices : false);
        //        }
        //        return showAddCommand;
        //    }
        //}

        //private void AddInvoice()
        //{
        //    //Link link = new Link();
        //    //Uri uri = new Uri("0", UriKind.Relative);
        //    //link.Source = uri;
        //    ////InvoiceLinks.Add(link);
        //    //SelectedLink = link.Source;
           
        //    this.OnPropertyChanged("SelectedLink");
        //}

        private ICommand showSaveCommand;

        public ICommand ShowSaveCommand
        {
            get
            {
                if (showSaveCommand == null)
                {
                    showSaveCommand = new Common.CommandBase(
                        i => this.SaveInvoice(),
                        i => ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ?
                            ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).EditInvoices : false);
                }
                return showSaveCommand;
            }
        }

        private void SaveInvoice()
        {
            try
            {
                SelectedInvoice.ShowSaveCommand.Execute(null);
                this.OnPropertyChanged("Invoices");
                this.OnPropertyChanged("SelectedInvoice");
            }
            catch (Exception ex)
            { ModernDialog.ShowMessage(ex.Message, "Save Client Failed", MessageBoxButton.OK); }
        }
        private ICommand showDeleteCommand;

        public ICommand ShowDeleteCommand
        {
            get
            {
                if (showDeleteCommand == null)
                {
                    showDeleteCommand = new Common.CommandBase(
                        i => this.DeleteInvoice(),
                        i => this.CanDelete());
                }
                return showDeleteCommand;
            }
        }

        private void DeleteInvoice()
        {
            var result = ModernDialog.ShowMessage(string.Format("Do you want to delete invoice number {0} from {1}?",
                SelectedInvoice.Number, SelectedInvoice.Date.ToString("MMMM dd, yyyy")), "Delete Invoice Dialog", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    SelectedInvoice.Delete();
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage(ex.Message, "Delete Invoice Failed", MessageBoxButton.OK);
                }
            }
            this.OnPropertyChanged("Invoices");
            this.OnPropertyChanged("SelectedInvoice");
            
        }
        private bool CanDelete()
        {
            if (object.Equals((UserViewModel)Properties.Settings.Default.AuthenticatedUser, null)) return false;
            if (object.Equals(SelectedInvoice, null)) return false;
            return ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).DeleteInvoices;
        }

        ////for opening up the Add Client window
        //private ICommand printCommand;

        //public ICommand PrintCommand
        //{
        //    get
        //    {
        //        if (printCommand == null)
        //        {
        //            printCommand = new Common.CommandBase(
        //                i => this.PrintInvoice(),
        //                i => ((UserViewModel)Properties.Settings.Default.AuthenticatedUser) != null ? ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).PrintInvoices : false);
        //        }
        //        return printCommand;
        //    }
        //}

        //private void PrintInvoice()
        //{
        //    new Common.InvoiceDocument(SelectedInvoice, string.Format("{0}\\{1}-{2}.pdf", EasyInvoice.WPF.Properties.Settings.Default.ExportFolderLocation, SelectedInvoice.Number, SelectedInvoice.Date.ToString("yyyy-MM-dd")));
        //    var result = ModernDialog.ShowMessage(
        //        string.Format("Invoice Number {0} from {1} is saved to file {0}-{2}.pdf. \nDo  you want to open it?", SelectedInvoice.Number, SelectedInvoice.Date.ToString("MMMM dd, yyyy"), SelectedInvoice.Date.ToString("yyyy-MM-dd"))
        //        , "Invoice Exported to pdf", MessageBoxButton.YesNo);
        //    if (result == MessageBoxResult.Yes)
        //        Process.Start(string.Format("{0}\\{1}-{2}.pdf", EasyInvoice.WPF.Properties.Settings.Default.ExportFolderLocation, SelectedInvoice.Number, SelectedInvoice.Date.ToString("yyyy-MM-dd")));
        //}

     
        private ICommand refreshCommand;

        public ICommand RefreshCommand
        {
            get
            {
                if (refreshCommand == null)
                {
                    refreshCommand = new Common.CommandBase(i => this.RefreshInvoices(), null);
                }
                return refreshCommand;
            }
        }

        private void RefreshInvoices()
        {
            //save client
            this.OnPropertyChanged("Invoices");
        }
    }

}
